﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using SaveExcel;

namespace MesForm.Common
{
    public class FileTool
    {
        //当前程序所在目录
        public static string BasePath = AppDomain.CurrentDomain.BaseDirectory;
        private string _MesLogPath = @"D:\MESLOG\";
        public static string SavePath = string.Empty;
        /// <summary>
        /// 上场保存路径
        /// </summary>
        public string MesLogPath
        {
            get { return _MesLogPath; }
            set { _MesLogPath = value; }
        }


        private DataTable _dtMesLog;
        /// <summary>
        /// 
        /// </summary>
        public DataTable DtMesLog
        {
            get { return _dtMesLog; }
            set { _dtMesLog = value; }
        }
        public FileTool()
        {
            InitDtMesLog();            
        }
        /// <summary>
        /// 
        /// </summary>
        private void InitDtMesLog()
        {
            //表头
            //static string header = "操作人员,生产机台编号,工序代码,mes上传地址,电芯条码/托盘,mes上传数据,结果,mes返回数据,开始时间,结束时间,测试时间(毫秒)";
            // _mesLog.LogTitle = @"时间 [Request/Response] [CommandID] [RequestDate] [MessageGuid] [RequestJson/ResponseJson]";
            _dtMesLog = new DataTable();
            _dtMesLog.Columns.Add("操作人员");// 
            _dtMesLog.Columns.Add("生产机台编号");// 
            _dtMesLog.Columns.Add("工序代码");// 
            _dtMesLog.Columns.Add("mes上传地址");// 
            _dtMesLog.Columns.Add("电芯条码/托盘");// 
            _dtMesLog.Columns.Add("mes上传数据");// 
            _dtMesLog.Columns.Add("结果");//
            _dtMesLog.Columns.Add("mes返回数据");//
            _dtMesLog.Columns.Add("开始时间");//
            _dtMesLog.Columns.Add("结束时间");//
            _dtMesLog.Columns.Add("测试时间(毫秒)");//

        }
        /// <summary>
        /// 保存MES数据
        /// </summary>
        /// <param name="rtnDR"></param>
        //欣旺达格式、路径及命名规则：
        //1、日志格式：包含请求时间、地址、参数、MES返回内容等，具体详见附件
        //2、日志路径及命名规则：建议统一保存D:\MESLOG\接口名（MES接口名+中文）\年+月（如202207），如D:\MESLOG\ LoginCheck登录接口\202207\2022071701（正常每班次一个文件，如数据较大的可4-6小时一个文件）
        public void SaveMesLog(DataRow rtnDR,string mesName)
        {
            string tmpErr = string.Empty;
            //string saveDataPath = GlobalDefine.ParamCfgCls.GetParamValue((int)ESysParamType.Customize, (int)ESysParam.ProdDataSavePath);
            //string[] arryPath = saveDataPath.Split(';');
            int saveFlag = 1;
            string filePath = string.Empty;

            //if (arryPath.Length > 1)
            //{
            //    saveFlag = Convert.ToInt32(arryPath[0]);
            //    filePath = arryPath[1];
            //}
            //else
            //    filePath = arryPath[0];
            if (string.IsNullOrEmpty(SavePath))
                filePath = $"D:\\MESLOG\\{mesName}";
            else
                filePath = SavePath + $"\\{mesName}";

            if (saveFlag > 0)
            {
                string fileName = DateTime.Now.ToString("yyyyMMdd") + ".csv";
                filePath = filePath + "\\" + fileName;

                // 检查文件是否已经存在并且被打开
                if (File.Exists(filePath))
                {
                    try
                    {
                        // 尝试打开文件以检查是否被占用
                        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                        {
                            // 文件没有被占用，可以正常写入
                        }
                    }
                    catch (IOException)
                    {
                        // 文件被占用，创建副本文件
                        string copyFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_copy.csv";
                        string copyFilePath = Path.Combine(Path.GetDirectoryName(filePath), copyFileName);
                        filePath = copyFilePath;
                    }
                }

                DataTable dt = _dtMesLog.Clone();
                dt.ImportRow(rtnDR);
                string headTxt = string.Empty;
                SaveCSV(dt, headTxt, filePath, out tmpErr);
            }
        }

        public void SaveMesOutLog(string commandID, string strComMsg)
        {
            string strSub = "SaveMesOutLog";
            try
            {
                //DataLogInfo.SaveLogtDataCSV(sTitle, strValue, "测试1");
                SaveMesTxtActionLog(commandID, strComMsg);
            }
            catch (Exception ex)
            {

            }
        }

        static object MeslogInfoLock = new object();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strAction">所调用接口名</param>
        /// <param name="strSendjsData">所传输数据</param>
        /// <param name="strCostTimeMsg">花费时间信息</param>
        public void SaveMesTxtActionLog(string strAction, string strSendjsData, string strCostTimeMsg = "", string strResponseData = "")
        {
            string strMessage = "";
            if (!_MesLogPath.EndsWith("\\"))
                _MesLogPath += "\\";
            string strPath = string.Format("{0}{1}\\", _MesLogPath, strAction);
            try
            {
                lock (MeslogInfoLock)
                {
                    //frmMain.MesMsgLst.Add(strMessage); 
                    //if (strMessageErrPrive == strMessage) return;
                    //strMessageErrPrive = strMessage;

                    if (!string.IsNullOrEmpty(strResponseData))
                        strMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "->" + string.Format("{0},{1},Rcv:{2}", strCostTimeMsg, strSendjsData, strResponseData);
                    else
                        strMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "->" + string.Format("{0},{1}", strCostTimeMsg, strSendjsData);
                    if (string.IsNullOrEmpty(strPath)) strPath = @"D:\Meslog\";//处理日志路径问题 20220807 0805 
                    if (!Directory.Exists(strPath))
                    {
                        Directory.CreateDirectory(strPath);
                    }
                    StreamWriter LogSw = new StreamWriter(strPath + DateTime.Today.ToString("yyyy-MM-dd") + ".txt", true, Encoding.GetEncoding(0));
                    strMessage += "\r";
                    strMessage += " ----------------------- split -----------------------\r";
                    LogSw.WriteLine(strMessage);
                    LogSw.Flush();
                    LogSw.Close();
                    LogSw.Dispose();
                }

            }
            catch (Exception ex)
            {

            }
        }
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void SaveCSV(DataTable dt, string headTxt, string fullPath, out string errStr)
        {
            errStr = string.Empty;
            try
            {
                FileInfo fileInfo = new FileInfo(fullPath);
                bool flag = false;
                if (!File.Exists(fullPath))
                {
                    flag = true;
                    fileInfo.Directory.Create();
                }
                FileStream fileStream = new FileStream(fullPath, FileMode.Append, FileAccess.Write);
                StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
                string text = "";
                if (flag)
                {
                    if (string.IsNullOrEmpty(headTxt))
                    {
                        string text2 = "";
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            text2 += dt.Columns[i].ColumnName.ToString();
                            if (i < dt.Columns.Count - 1)
                            {
                                text2 += ",";
                            }
                        }
                        streamWriter.WriteLine(text2);
                    }
                    else
                    {
                        streamWriter.WriteLine(headTxt);
                    }
                }
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    text = "";
                    for (int k = 0; k < dt.Columns.Count; k++)
                    {
                        string text3 = dt.Rows[j][k].ToString();
                        text3 = text3.Replace("\"", "\"\"");
                        if (text3.Contains(',') || text3.Contains('"') || text3.Contains('\r') || text3.Contains('\n'))
                        {
                            text3 = $"\"{text3}\"";
                        }
                        text += text3;
                        if (k < dt.Columns.Count - 1)
                        {
                            text += ",";
                        }
                    }
                    streamWriter.WriteLine(text);
                }
                streamWriter.Close();
                fileStream.Close();
            }
            catch (Exception ex)
            {
                errStr = ex.Message;
            }
        }
        //public void Record(string record, string header, string position)
        //{
        //    try
        //    {
        //        string dateTime = DateTime.Now.ToString("yyyyMMdd");
        //        if (!File.Exists($"D:\\MesData\\{position}\\{dateTime}.csv"))
        //        {
        //            Directory.CreateDirectory($"D:\\MesData\\{position}");
        //        }
        //        if (!File.Exists($"D:\\MesData\\{position}\\{dateTime}.csv"))
        //        {
        //            //Directory.CreateDirectory($"D:\\MesData\\{position}\\{dateTime}.csv");
        //            using (StreamWriter writer = new StreamWriter($"D:\\MesData\\{position}\\{dateTime}.csv"))
        //            {
        //                // 写入表头
        //                writer.WriteLine(header);

        //                // 写入数据
        //                writer.WriteLine(record);
        //            };
        //        }
        //        else
        //        {
        //            using (StreamWriter writer = new StreamWriter($"D:\\MesData\\{position}\\{dateTime}.csv"))
        //            {
        //                // 写入数据
        //                writer.WriteLine(record);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {

        //    }
        //}
    }
}
